import {VNodeFlags,ChildrenFlags} from './flags'

export const Fragment = Symbol();
export const PORTAL = Symbol();

export function h(tag,data=null,children=null){
    let flags = null;
    if(typeof tag === 'string'){  //html svg除外
        // 代码的可读性
        flags = tag ==='svg' ?  VNodeFlags.ELEMENT_SVG:VNodeFlags.ELEMENT_HTML ;
    }
    else if(tag===Fragment){
        flags = VNodeFlags.FRAGMENT;
    }
    else if(tag === PORTAL){
        flags = VNodeFlags.PORTAL
        tag=data && data.target
    }
    else{
        // 组件
        if(tag != null && typeof tag === 'object'){
            flags = tag.functional ? VNodeFlags.COMPONENT_FUNCTIONAL : VNodeFlags.STATE_FULL_NORMAL
        }
        else if (typeof tag === 'function'){
            // 箭头函数
            flags = tag.prototype && tag.prototype.render ? VNodeFlags.COMPONENT_STATEFUL_NORMAL : VNodeFlags.COMPONENT_FUNCTIONAL
        }
    }

    // console.log(tag,flags)


    // tag 有多种类型
    // & | 位运算
    // 0000 0010
    // 0000 0001
    // & 0
    // | 3
    // CPU 做加减法不如位运算快
    // children 也有多种肯能
    // 1. string 文本
    // 2. 数组  节点
    // 3. null


    // child Flag 处理

    let childFlags = null
    if(Array.isArray(children)){
        // Array.isArray  兼容问题
        const {length} = children
        if(length === 0){
            childFlags=ChildrenFlags.NO_CHILDERN
        }
        else if(length === 1){
            childFlags=ChildrenFlags.SINGLE_VNODE
            children = children[0]
        }
        else {
            childFlags = ChildrenFlags.KEYED_VNODES;   //  分支
            children = normalizeVNode(children);
        }
    }
    else if(children === null){
        childFlags=ChildrenFlags.NO_CHILDERN
    }
    else if(children._isVNode){  // 
        childFlags = ChildrenFlags.SINGLE_VNODE
    }
    else{
        childFlags=ChildrenFlags.SINGLE_VNODE;
        children = createTextVNode(children+'')
    }

    return {
        _isVNode:true,
        flags,    // 容器节点的类型
        childFlags,
        data,
        children,
        el:null,
        tag,
        name:11
    }
}

function normalizeVNode(children){
    const newChildren = []
    for(let i = 0;i<children.length;i++){
        const child = children[i];
        if(child.key == null){
            child.key = '|' + i
        }
        newChildren.push(child)
    }
    return newChildren
}

function createTextVNode(text){
    return {
        _isVNode:true,
        flags:VNodeFlags.TEXT,
        tag:null,
        data:null,
        children:text,
        childFlags:ChildrenFlags.NO_CHILDERN
    }
}